<template>
	<view class="">
		<titleBar title="品牌详情" :isSubPage="true"></titleBar>
		<view class="container">
			<!-- 店铺信息区域 -->
			<view class="shop-info">
				<image :src="brandInfo.avatar" mode="aspectFill" class="shop-logo"></image>
				<view class="shop-detail">
					<text class="shop-name">{{ brandInfo.shopName }}</text>
					<view class="shop-stats">
						<text class="shop-stat">商品: {{ allProducts.length }}</text>
						<text class="shop-stat">关注: {{ brandInfo.attention }}</text>
					</view>
					<view class="shop-stats">
						<text>{{ brandInfo.shopDescription }}</text>
					</view>
					<view class="shop-buttons">
						<!-- <button class="btn-follow" :class="{ 'followed': brandInfo.isFollowed }" @click="toggleFollow">
							{{ brandInfo.isFollowed ? '已关注' : '关注店铺' }}
						</button> -->
						<button class="btn-contact" @click="contactShop">联系客服</button>
					</view>
				</view>
			</view>

			<!-- 主内容区域 -->
			<view class="main-content">
				<!-- 左侧导航栏 -->
				<scroll-view class="sidebar" scroll-y="true">
					<view class="sidebar-item" v-for="(category, index) in categories" :key="index"
						:class="{ 'active': currentCategory === index }" @click="selectCategory(index)">
						{{ category.name }}
					</view>
				</scroll-view>

				<!-- 右侧商品列表 -->
				<scroll-view class="product-list" scroll-y="true" @scrolltolower="loadMoreProducts">
					<!-- 初始提示 -->
					<view class="empty-state" v-if="!selectedCategory">
						<image src="/static/pet-test.png" mode="aspectFit" class="empty-icon"></image>
						<text class="empty-text">请选择左侧分类查看商品</text>
					</view>

					<block v-else>
						<!-- 商品筛选栏 -->
						<view class="filter-bar">
							<view class="filter-item" v-for="(filter, index) in filters" :key="index"
								:class="{ 'active': currentFilter === index }" @click="applyFilter(index)">
								{{ filter.name }}
							</view>
						</view>

						<!-- 商品为空提示 -->
						<view class="no-products" v-if="filteredProducts.length === 0 && !isLoading">
							<text>暂无商品</text>
						</view>

						<!-- 商品网格 -->
						<view class="product-grid" v-else>
							<view class="product-item" v-for="(product, index) in filteredProducts" :key="product.id"
								@click="navigateToDetail(product.id)">
								<image :src="product.image" mode="aspectFill" class="product-image"></image>
								<view class="product-info">
									<text class="product-name">{{ product.name }}</text>
									<view class="product-price-row">
										<text class="product-price">¥{{ product.price.toFixed(2) }}</text>
										<text class="product-original-price" v-if="product.originalPrice">
											¥{{ product.originalPrice.toFixed(2) }}
										</text>
									</view>
									<view class="product-tags">
										<view class="product-tag" v-for="(tag, tagIndex) in product.tags"
											:key="tagIndex">
											{{ tag }}
										</view>
									</view>
									<view class="product-sales">销量: {{ product.salesCount }}</view>
								</view>
							</view>
						</view>

						<!-- 加载更多 -->
						<view class="loading-more" v-if="isLoading">
							<text>加载中...</text>
						</view>
						<view class="no-more" v-if="noMoreData && filteredProducts.length > 0">
							<text>没有更多商品了</text>
						</view>
					</block>
				</scroll-view>
			</view>
		</view>
	</view>
</template>

<script>
	import titleBar from '@/components/titleBar.vue'
	import {
		productApi
	} from '@/api/user.js'
	export default {
		components: {
			titleBar
		},
		data() {
			return {
				brandId: null,
				brandInfo: '',
				// {
				// 	id: 1,
				// 	name: '品牌名称',
				// 	logo: '/static/pet-test.png',
				// 	productCount: 568,
				// 	followerCount: 2354,
				// 	isFollowed: false
				// },
				categories: [{
						id: 1,
						name: '全部商品',
						tagFilter: null
					},
					{
						id: 2,
						name: '热销榜单',
						tagFilter: '热销'
					},
					{
						id: 3,
						name: '新品上市',
						tagFilter: '新品'
					},
					{
						id: 4,
						name: '限时折扣',
						tagFilter: '折扣'
					}
				],
				currentCategory: 0, // 初始为null，表示未选择任何分类
				selectedCategory: true, // 标记是否已选择分类
				filters: [{
						id: 1,
						name: '综合',
						sort: null
					},
					{
						id: 2,
						name: '销量',
						sort: 'sales'
					},
					{
						id: 3,
						name: '价格↑',
						sort: 'price_asc'
					},
					{
						id: 4,
						name: '价格↓',
						sort: 'price_desc'
					}
				],
				currentFilter: 0,
				products: [],
				allProducts: [], // 保存所有加载的商品，用于客户端排序
				isLoading: false,
				page: 1,
				pageSize: 10,
				noMoreData: false
			}
		},
		computed: {
			filteredProducts() {
				// 根据当前筛选条件进行排序
				const sortType = this.filters[this.currentFilter].sort;
				if (!sortType) return this.products; // 综合排序，使用默认顺序

				// 创建产品的副本进行排序
				let sortedProducts = [...this.products];

				switch (sortType) {
					case 'sales':
						// 销量排序（从高到低）
						sortedProducts.sort((a, b) => b.salesCount - a.salesCount);
						break;
					case 'price_asc':
						// 价格升序（从低到高）
						sortedProducts.sort((a, b) => a.price - b.price);
						break;
					case 'price_desc':
						// 价格降序（从高到低）
						sortedProducts.sort((a, b) => b.price - a.price);
						break;
					case 'new':
						// 新品排序（假设有一个上架时间字段，这里用ID模拟）
						sortedProducts.sort((a, b) => b.id - a.id);
						break;
				}

				return sortedProducts;
			}
		},
		mounted() {
			this.brandId = getApp().globalData.currentStored;
			this.fetchBrandInfo();
			this.applyFilter(0)
			this.fetchProducts()
		},
		methods: {
			// 获取品牌信息
			async fetchBrandInfo() {
				try {
					const result = await productApi.getStoreById({
						id: this.brandId
					})
					this.brandInfo = result
					console.log(result);
				} catch (error) {
					uni.showToast({
						title: '获取店铺商品失败: ' + (error.message || '未知错误'),
						icon: 'none'
					});
					console.error('获取店铺商品失败', error);
				}
			},

			// 获取商品列表
			async fetchProducts() {
				if (this.isLoading || this.noMoreData || this.currentCategory === null) return;

				this.isLoading = true;
				console.log('加载商品列表', this.currentCategory, this.currentFilter, this.page);

				try {
					const result = await productApi.getProductList()
					console.log(result);
					// 根据brandId筛选出当前店铺的商品
					let storeProducts = result.filter(item => item.shopId == this.brandId);
					// 将API返回的数据格式转换为组件需要的格式
					// 如果选择了特定分类（非全部商品），根据标签进行过滤
					const currentTagFilter = this.categories[this.currentCategory].tagFilter;
					if (currentTagFilter) {
						storeProducts = storeProducts.filter(item => {
							const tags = item.label ? item.label.split(',') : [];
							return tags.includes(currentTagFilter);
						});
					}
					const formattedProducts = storeProducts.map(item => {
						// 将标签字符串转换为数组
						const tags = item.label ? item.label.split(',') : [];
						return {
							id: item.id,
							name: item.tradeName, // 将tradeName映射为name
							price: item.prices, // 将prices映射为price
							originalPrice: null, // API没有提供原价，设为null
							tags: tags, // 将label分割为标签数组
							image: item.picture || '/static/pet-test.png', // 如果没有图片则使用默认图片
							salesCount: item.salesVolume || 0, // 销量，如果为null则默认为0
							createTime: new Date(item.createTime).getTime() // 创建时间转为时间戳
						};
					});
					// 更新商品列表
					this.products = [...this.products, ...formattedProducts];
					this.allProducts = [...this.allProducts, ...formattedProducts];
					// 判断是否还有更多数据
					if (formattedProducts.length < this.pageSize) {
						this.noMoreData = true;
						this.isLoading = false;
					} else {
						this.page++;
					}
				} catch (error) {
					uni.showToast({
						title: '获取店铺商品失败: ' + (error.message || '未知错误'),
						icon: 'none'
					});
					console.error('获取店铺商品失败', error);
				}
			},
			// 选择分类
			selectCategory(index) {
				if (this.currentCategory === index) return;

				this.currentCategory = index;
				this.selectedCategory = true; // 标记已选择分类
				this.resetProductList();
				this.fetchProducts();
			},

			// 重置商品列表
			resetProductList() {
				this.products = [];
				this.allProducts = [];
				this.page = 1;
				this.noMoreData = false;
				this.currentFilter = 0; // 重置为"综合"排序
			},

			// 应用筛选
			applyFilter(index) {
				console.log(index);
				if (this.currentFilter === index) return;

				this.currentFilter = index;

				// 价格筛选使用客户端排序而不是重新加载
				const sortType = this.filters[index].sort;
				if (sortType === 'sales' || sortType === 'price_asc' || sortType === 'price_desc') {
					// 不重新加载数据，直接使用已有数据排序
					return;
				}

				// 其他筛选方式重新加载数据
				this.resetProductList();
				this.fetchProducts();
			},

			// 关注/取消关注店铺
			toggleFollow() {
				this.brandInfo.isFollowed = !this.brandInfo.isFollowed;

				// 实际中这里应该调用API
				if (this.brandInfo.isFollowed) {
					this.brandInfo.followerCount++;
					uni.showToast({
						title: '已关注店铺',
						icon: 'none'
					});
				} else {
					this.brandInfo.followerCount--;
					uni.showToast({
						title: '已取消关注',
						icon: 'none'
					});
				}
			},

			// 联系店铺
			contactShop() {
				uni.showToast({
					title: '客服功能即将上线',
					icon: 'none'
				});
			},

			// 加载更多商品
			loadMoreProducts() {
				this.fetchProducts();
			},

			// 跳转到商品详情
			navigateToDetail(id) {
				getApp().globalData.currentGoodId = id;
				uni.navigateTo({
					url: `/pages/shop/goods?id=${id}`
				});
			}
		}
	}
</script>

<style>
	.container {
		padding: 0 20rpx;
		background-color: #f5f5f5;
		height: 100vh;
		display: flex;
		flex-direction: column;
	}

	/* 店铺信息样式 */
	.shop-info {
		display: flex;
		align-items: center;
		background-color: #fff;
		padding: 30rpx 10rpx;
		border-radius: 12rpx;
		margin-bottom: 20rpx;
		margin-top: 20rpx;
	}

	.shop-logo {
		width: 120rpx;
		height: 120rpx;
		border-radius: 50%;
		border: 2rpx solid #f0f0f0;
	}

	.shop-detail {
		flex: 1;
		margin-left: 20rpx;
	}

	.shop-name {
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 10rpx;
	}

	.shop-stats {
		display: flex;
		font-size: 24rpx;
		color: #666;
		margin-bottom: 15rpx;
	}

	.shop-stat {
		margin-right: 20rpx;
	}

	.shop-buttons {
		display: flex;
	}

	.btn-follow,
	.btn-contact {
		padding: 8rpx 20rpx;
		font-size: 24rpx;
		border-radius: 30rpx;
		margin-right: 15rpx;
		background-color: #FF6B6B;
		color: #fff;
		border: none;
	}

	.btn-follow.followed {
		background-color: #f0f0f0;
		color: #666;
	}

	.btn-contact {
		background-color: #fff;
		color: #FF6B6B;
		border: 1rpx solid #FF6B6B;
	}

	/* 主内容区域样式 */
	.main-content {
		display: flex;
		flex: 1;
		overflow: hidden;
	}

	/* 左侧导航栏样式 */
	.sidebar {
		width: 190rpx;
		background-color: #fff;
		border-radius: 12rpx;
		height: 100%;
	}

	.sidebar-item {
		padding: 30rpx 20rpx;
		font-size: 26rpx;
		text-align: center;
		border-bottom: 1rpx solid #f5f5f5;
		color: #333;
	}

	.sidebar-item.active {
		color: #FF6B6B;
		font-weight: bold;
		width: 190rpx;
		position: relative;
	}

	.sidebar-item.active::before {
		content: '';
		position: absolute;
		left: 0;
		top: 30%;
		height: 40%;
		width: 6rpx;
		background-color: #FF6B6B;
	}

	/* 右侧商品列表样式 */
	.product-list {
		flex: 1;
		margin-left: 20rpx;
		height: 100%;
	}

	/* 初始空状态样式 */
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 0;
	}

	.empty-icon {
		width: 200rpx;
		height: 200rpx;
		opacity: 0.5;
		margin-bottom: 30rpx;
	}

	.empty-text {
		font-size: 28rpx;
		color: #999;
	}

	/* 无商品提示 */
	.no-products {
		text-align: center;
		padding: 100rpx 0;
		font-size: 28rpx;
		color: #999;
	}

	/* 筛选栏样式 */
	.filter-bar {
		display: flex;
		background-color: #fff;
		padding: 20rpx;
		border-radius: 12rpx;
		margin-bottom: 20rpx;
		overflow-x: auto;
		white-space: nowrap;
	}

	.filter-item {
		padding: 10rpx 20rpx;
		font-size: 24rpx;
		color: #666;
		margin-right: 15rpx;
	}

	.filter-item.active {
		color: #FF6B6B;
		font-weight: bold;
		position: relative;
	}

	.filter-item.active::after {
		content: '';
		position: absolute;
		bottom: 0;
		left: 20%;
		width: 60%;
		height: 4rpx;
		background-color: #FF6B6B;
	}

	/* 商品网格样式 */
	.product-grid {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
	}

	.product-item {
		width: 48%;
		background-color: #fff;
		border-radius: 12rpx;
		overflow: hidden;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.product-image {
		width: 100%;
		height: 300rpx;
	}

	.product-info {
		padding: 16rpx;
	}

	.product-name {
		font-size: 26rpx;
		color: #333;
		margin-bottom: 10rpx;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;
		height: 76rpx;
	}

	.product-price-row {
		display: flex;
		align-items: center;
		margin-bottom: 10rpx;
	}

	.product-price {
		font-size: 32rpx;
		font-weight: bold;
		color: #FF6B6B;
	}

	.product-original-price {
		font-size: 24rpx;
		color: #999;
		text-decoration: line-through;
		margin-left: 10rpx;
	}

	.product-tags {
		display: flex;
		flex-wrap: wrap;
		margin-bottom: 6rpx;
	}

	.product-tag {
		font-size: 20rpx;
		color: #FF6B6B;
		background-color: rgba(255, 107, 107, 0.1);
		padding: 2rpx 8rpx;
		margin-right: 8rpx;
		margin-bottom: 6rpx;
		border-radius: 4rpx;
	}

	.product-sales {
		font-size: 22rpx;
		color: #999;
	}

	/* 加载更多样式 */
	.loading-more,
	.no-more {
		text-align: center;
		padding: 20rpx 0;
		font-size: 24rpx;
		color: #999;
	}
</style>